/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.star.framework.excel.handler.settings.HeaderComment;
import cn.star.framework.excel.handler.settings.HeaderComment.Comment;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

/**
 * 支持表头使用注释<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public class CellHeaderCommentHandler implements CellWriteHandler, OrderHandler {

  private final HeaderComment setting;

  public CellHeaderCommentHandler(List<Comment> comments) {
    this(new HeaderComment(comments));
  }

  public CellHeaderCommentHandler(HeaderComment setting) {
    this.setting = setting;
  }

  @Override
  public void afterCellDispose(
      WriteSheetHolder writeSheetHolder,
      WriteTableHolder writeTableHolder,
      List<WriteCellData<?>> cellDataList,
      Cell cell,
      Head head,
      Integer relativeRowIndex,
      Boolean isHead) {
    boolean needSetWidth = isHead || CollectionUtil.isNotEmpty(cellDataList);
    List<Comment> comments = setting.getComments();
    if (needSetWidth && CollectionUtil.isNotEmpty(comments)) {
      int rowIndex = cell.getRowIndex();
      int colIndex = cell.getColumnIndex();

      List<Comment> vos =
          comments.stream()
              .filter(
                  vo -> vo != null && vo.getRowIndex() == rowIndex && vo.getColIndex() == colIndex)
              .collect(Collectors.toList());

      if (CollectionUtil.isNotEmpty(vos)) {
        Comment vo = vos.stream().findFirst().orElse(null);
        if (vo != null && StrUtil.isNotEmpty(vo.getText())) {
          Sheet sheet = cell.getSheet();
          ClientAnchor anchor = new XSSFClientAnchor();

          anchor.setDx1(0);
          anchor.setDy1(0);
          anchor.setDx2(0);
          anchor.setDy2(0);

          anchor.setRow1(rowIndex);
          anchor.setCol1(colIndex);
          anchor.setRow2(rowIndex + vo.getRowOffset());
          anchor.setCol2(colIndex + vo.getColOffset());

          Drawing<?> drawing = sheet.createDrawingPatriarch();

          org.apache.poi.ss.usermodel.Comment comment = drawing.createCellComment(anchor);
          comment.setString(new XSSFRichTextString(vo.getText()));
          if (StrUtil.isNotBlank(vo.getAuthor())) {
            // java.lang.NullPointerException
            comment.setAuthor(vo.getAuthor());
          }
          cell.setCellComment(comment);
        }
      }
    }
  }

  @Override
  public int order() {
    return this.wrapper(OrderStrategyType.CELL_HEADER_COMMENT);
  }
}
